#include "stdafx.h"
#include "GuiTaskManager.h"

GuiTaskManager::GuiTaskManager(QObject *parent)
    : QObject(parent), taskHelperTimer(this)
{
    QObject::connect(&taskHelperTimer, &QTimer::timeout, this, &GuiTaskManager::on_taskHelperTimerTimeout);
    taskHelperTimer.start(1);
}

GuiTaskManager::~GuiTaskManager()
{

}

std::shared_ptr<std::atomic<bool>> GuiTaskManager::guiTask(std::function<void()> func)
{
    std::lock_guard<std::mutex> g(helpTasksMutex);
    std::shared_ptr<std::atomic<bool>> atomicBool = std::make_shared<std::atomic<bool>>(false);
    helpTasks.emplace_back(atomicBool, func);
    return atomicBool;
}

void GuiTaskManager::on_taskHelperTimerTimeout()
{
    if (helpTasks.size())
    {
        std::lock_guard<std::mutex> g(helpTasksMutex);
        while (helpTasks.size())
        {
            std::pair<std::shared_ptr<std::atomic<bool>>, std::function<void()>> package = helpTasks.front();
            package.second();
            package.first->store(true);
            helpTasks.pop_front();
        }
    }
}